<?php defined('SYSPATH') or die('No direct script access.');

class Controller_Membergrade extends Stourweb_Controller
{

    public function before()
    {
        parent::before();

        $this->assign('parentkey', $this->params['parentkey']);
        $this->assign('itemid', $this->params['itemid']);
        $this->assign('weblist', Common::getWebList());
    }

    /**
     * 广告列表
     */
    public function action_index()
    {
        $action = is_null($this->params['action']) ? 'null' : $this->params['action'];
        switch ($action)
        {
            case 'null':
                $this->display('stourtravel/membergrade/list');
                break;
            case 'read':
                $start = Arr::get($_GET, 'start');
                $limit = Arr::get($_GET, 'limit');
                $keyword = Arr::get($_GET, 'keyword');

                $cfg_member_grade_rule = DB::select()->from('sysconfig')
                    ->where('varname','=','cfg_member_grade_rule')
                    ->execute()->get('value');

                $model = DB::select()->from('member_grade')->where('id','>',0);
                if($keyword){
                    $model->and_where('name','like','%'.$keyword.'%');
                }
                $total = $model->execute()->count();
                if($cfg_member_grade_rule==3){
                    $model->order_by('price','asc');
                }else{
                    $model->order_by('begin','asc');
                }

                $model->offset($start)->limit($limit);
                $list = $model->execute()->as_array();

                foreach ($list as $k => &$v)
                {
                    if($v['grade_rules']==1){
                        $v['section'] = $v['begin'].'~'.$v['end'];
                    }else{
                        $v['section'] = '充值'.$v['price'].'元';
                    }

                    if($v['is_system']==1){
                        $v['member_num'] = DB::select()->from('member')->where("grade_id={$v['id']} OR grade_id='' OR grade_id IS NULL")->execute()->count();
                    }else{
                        $v['member_num'] = DB::select()->from('member')->where('grade_id','=',$v['id'])->execute()->count();
                    }
                }

                $result['total']   = $total;
                $result['lists']   = $list;
                $result['success'] = true;
                echo json_encode($result);
                break;
            case 'delete':
                $rawdata = file_get_contents('php://input');
                $data = json_decode($rawdata);
                $id = $data->id;
                if (is_numeric($id))
                {
                    $sql = "delete from sline_member_grade where id={$id}";
                    $total_rows = DB::query(Database::DELETE, $sql)->execute();
                    if($total_rows){
                        DB::delete('member_grade_equity')->where('grade_id', '=', $id)->execute();
                    }
                    echo $total_rows > 0 ? 'ok' : 'no';
                }
                break;
        }
    }

    /**
     * 添加
     */
    public function action_add()
    {
        $ty_equity                 = DB::select()->from('member_equity')
            ->where('ishidden', '=', '0')
            ->and_where('is_system', '=', '1')
            ->execute()->as_array();
        $zdy_equity                = DB::select()->from('member_equity')
            ->where('ishidden', '=', '0')
            ->and_where('is_system', '=', '0')
            ->execute()->as_array();
        $cfg_member_grade_rule = DB::select()->from('sysconfig')
            ->where('varname','=','cfg_member_grade_rule')
            ->execute()->get('value');
        $grade_list = DB::select()->from('member_grade')->execute()->as_array();

        $this->assign('grade_list',$grade_list);
        $this->assign('grade_rule', $cfg_member_grade_rule);
        $this->assign('style_img', Model_Member::$equity_style_img);
        $this->assign('ty_equity', $ty_equity);
        $this->assign('zdy_equity', $zdy_equity);
        $this->assign('action', 'add');
        $this->assign('title', '会员等级');
        $this->display('stourtravel/membergrade/edit');
    }

    /**
     * 修改广告
     */
    public function action_edit()
    {
        $id = $this->params['id'];
        $info = DB::query(Database::SELECT, "select a.* from sline_member_grade AS a where a.id={$id}")->execute()->as_array();
        $info = $info[0];

        $ty_equity                 = DB::select()->from('member_equity')
            ->where('ishidden', '=', '0')
            ->and_where('is_system', '=', '1')
            ->execute()->as_array();
        $zdy_equity                = DB::select()->from('member_equity')
            ->where('ishidden', '=', '0')
            ->and_where('is_system', '=', '0')
            ->execute()->as_array();
        $grade_equity              = DB::select()->from('member_grade_equity')->where('grade_id', '=', $id)->execute()->current();
        $grade_equity['equity_id'] = explode(',', $grade_equity['equity_id']);
        $grade_equity['style_id']  = $grade_equity['style_id']?:1;
        if (St_Functions::is_normal_app_install('system_coupon')) {
            if ($grade_equity['birthday_coupon_id']) {
                $grade_equity['birthday_coupon_num'] = json_decode($grade_equity['birthday_coupon_num'], true);
                $grade_equity['birthday_coupon']     = Model_Coupon::get_coupon_info($grade_equity['birthday_coupon_id']);
            }
            if ($grade_equity['upgrade_coupon_id']) {
                $grade_equity['upgrade_coupon_num'] = json_decode($grade_equity['upgrade_coupon_num'], true);
                $grade_equity['upgrade_coupon']     = Model_Coupon::get_coupon_info($grade_equity['upgrade_coupon_id']);
            }
            if ($grade_equity['new_user_coupon_id']) {
                $grade_equity['new_user_coupon_num'] = json_decode($grade_equity['new_user_coupon_num'], true);
                $grade_equity['new_user_coupon']     = Model_Coupon::get_coupon_info($grade_equity['new_user_coupon_id']);
            }
        }
        $cfg_member_grade_rule = DB::select()->from('sysconfig')
            ->where('varname','=','cfg_member_grade_rule')
            ->execute()->get('value');

        $grade_list = DB::select()->from('member_grade')->execute()->as_array();

        $this->assign('style_img', Model_Member::$equity_style_img);
        $this->assign('grade_rule', $cfg_member_grade_rule);
        $this->assign('grade_equity', $grade_equity);
        $this->assign('grade_list', $grade_list);
        $this->assign('ty_equity', $ty_equity);
        $this->assign('zdy_equity', $zdy_equity);
        $this->assign('info', $info);
        $this->assign('action', 'edit');
        $this->assign('title', '修改会员等级');
        $this->display('stourtravel/membergrade/edit');
    }


    /**
     * ajax保存广告
     */
    public function action_ajax_save()
    {
        $status = false;

        $action = $_POST['action'];
        $id = intval($_POST['id']);

        $data_arr = NULL;
        $data_arr['name'] = trim($_POST['name']);
        $data_arr['begin'] = intval($_POST['begin']);
        $data_arr['end'] = intval($_POST['end']);

        $cfg_member_grade_rule = DB::select()->from('sysconfig')
            ->where('varname','=','cfg_member_grade_rule')
            ->execute()->get('value');

        if($cfg_member_grade_rule==3){
            //填写累计金额有效性检测
            $price = Arr::get($_POST, 'price');
            $rule_num = DB::select()->from('member_grade')->where('price','=',$price)->and_where('id','!=',$id)->execute()->count();
            $msg = '累计金额与其它规则重叠';
        }else{
            //填写积分区间有效性检测
            $where = '(('.$data_arr['begin'].'>=begin AND '.$data_arr['begin'].'<=end) OR ('.$data_arr['end'].'>=begin AND '.$data_arr['end'].'<=end))';
            if($id > 0)
            {
                $where .=  ' AND id<>'.$id;
            }
            $sql = "select count(0) AS num from sline_member_grade as a where {$where}";
            $rule_num = DB::query(Database::SELECT, $sql)->execute()->get('num');
            $msg = '积分区间与其它规则有重叠';
        }

        if ($rule_num > 0) {
            echo json_encode(array('status' => false,'msg'=>$msg));
            exit;
        } else {
            $data_arr['grade_rules'] = Arr::get($_POST, 'grade_rules');
            $data_arr['price'] = Arr::get($_POST, 'price');
            $data_arr['valid_type'] = Arr::get($_POST, 'valid_type');
            $data_arr['expiration_time'] = Arr::get($_POST, 'expiration_time');
            $data_arr['grade_id'] = Arr::get($_POST, 'grade_id');
            if($data_arr['expiration_time']<1){
                $data_arr['valid_type'] = 1;
            }
            if($data_arr['grade_id']){
                $dow_grade = DB::select()->from('member_grade')->where('id', '=', $data_arr['grade_id'])->execute()->get('begin');
                if($dow_grade>$data_arr['begin']){
                    echo json_encode(array(
                        'status' => false,
                        'msg'    => "到期降至等级不得高于当前等级！"
                    ));
                    exit;
                }
            }

            if ($action == 'add' && empty($id)) {
                $data_arr['addtime'] = time();
                $result = DB::insert('member_grade', array_keys($data_arr))->values(array_values($data_arr))->execute();
                if (is_array($result))
                {
                    $id = $result[0];
                    $status = true;
                }
            } else {
                $sql = array();
                $data_arr['modtime'] = time();

                foreach ($data_arr as $k => $v) {
                    array_push($sql, $k . "='{$v}'");
                }
                $sql = implode(',', $sql);
                $sql = "UPDATE `sline_member_grade` SET {$sql} WHERE `id` = {$id}";
                $result = DB::query(3, $sql)->execute();
                if ($result) {
                    $status = true;
                }
            }

            if($status){
                $equity_id           = Arr::get($_POST, 'equity_id');
                $birthday_coupon_id  = Arr::get($_POST, 'birthday_coupon_id');
                $upgrade_coupon_id   = Arr::get($_POST, 'upgrade_coupon_id');
                $new_user_coupon_id  = Arr::get($_POST, 'new_user_coupon_id');
                $birthday_coupon_num = Arr::get($_POST, 'birthday_coupon_num');
                $upgrade_coupon_num  = Arr::get($_POST, 'upgrade_coupon_num');
                $new_user_coupon_num = Arr::get($_POST, 'new_user_coupon_num');

                $equity = [
                    'content'            => Arr::get($_POST, 'content'),
                    'style_id'           => Arr::get($_POST, 'style_id'),
                    'gift_jifen'         => Arr::get($_POST, 'gift_jifen'),
                    'lottery_num'        => Arr::get($_POST, 'lottery_num'),
                    'equity_id'          => $equity_id?implode(',', $equity_id):'',
                    'birthday_coupon_id' => implode(',', $birthday_coupon_id),
                    'upgrade_coupon_id'  => implode(',', $upgrade_coupon_id),
                    'new_user_coupon_id' => implode(',', $new_user_coupon_id),
                    'birthday_coupon_num'=> json_encode($birthday_coupon_num),
                    'upgrade_coupon_num' => json_encode($upgrade_coupon_num),
                    'new_user_coupon_num'=> json_encode($new_user_coupon_num),
                ];

                $is_exist = DB::select()->from('member_grade_equity')->where('grade_id', '=', $id)->execute()->count();
                if ($is_exist) {
                    DB::update('member_grade_equity')->set($equity)->where('grade_id', '=', $id)->execute();
                } else {
                    $equity['grade_id'] = $id;
                    DB::insert('member_grade_equity', array_keys($equity))->values(array_values($equity))->execute();
                }
            }

            echo json_encode(array('status' => $status));
        }
    }

    public function action_dialog_coupon_list()
    {
        $action = $this->params['action'];
        if(empty($action)){
            $type = Arr::get($_GET, 'type');
            $select_id = Arr::get($_GET, 'select_id');

            $this->assign('type',$type);
            $this->assign('select_id',$select_id);
            $this->display('stourtravel/equity/dialog_coupon_list');
        }elseif($action=='read'){
            $params = [
                'start'     => Arr::get($_GET, 'start'),
                'limit'     => Arr::get($_GET, 'limit'),
                'keyword'   => Arr::get($_GET, 'keyword'),
                'coupon_id' => Arr::get($_GET, 'coupon_id'),
            ];
            $time  = time();
            $model = DB::select('id', 'name', 'starttime', 'endtime', 'totalnumber')
                ->from('coupon')
                ->where('isdel', '=', '0')
                ->and_where('usage_scenario', '=', 1)
                ->and_where(DB::expr(" and (endtime=0 || endtime>{$time}) "));
            if ($params['keyword']) {
                $model->and_where(DB::expr(" AND name LIKE '%{$params['keyword']}%' "));
            }
            if ($params['coupon_id']) {
                $model->and_where(DB::expr(" AND id NOT IN({$params['coupon_id']}) "));
            }
            $total = $model->execute()->count();
            $model->order_by('id', 'desc');
            $model->offset($params['start'])->limit($params['limit']);
            $coupon_list = $model->execute()->as_array();

            foreach ($coupon_list as &$v) {
                if ($v['starttime']) {
                    $start_time           = date('Y-m-d', $v['starttime']);
                    $end_time             = date('Y-m-d', $v['endtime']);
                    $v['validity_period'] = $start_time . ' 至 ' . $end_time;
                } else {
                    $v['validity_period'] = '永久有效';
                }
            }

            $res = [
                'total'   => $total,
                'lists'   => $coupon_list,
                'success' => true
            ];

            echo json_encode($res);
        }

    }

    public function action_dialog_set_grade_rule()
    {
        $cfg_member_grade_rule = DB::select()->from('sysconfig')
            ->where('varname','=','cfg_member_grade_rule')
            ->execute()->get('value');

        $this->assign('cfg_member_grade_rule',$cfg_member_grade_rule?:1);
        $this->display('stourtravel/membergrade/dialog_set_grade_rule');
    }

    public function action_ajax_save_rule()
    {
        $cfg_member_grade_rule = DB::select()->from('sysconfig')
            ->where('varname','=','cfg_member_grade_rule')
            ->execute()->get('value');
        $data = [
            'webid' => 0,
            'cfg_member_grade_rule' => Arr::get($_POST,'cfg_member_grade_rule'),
        ];
        Model_Sysconfig::save_config($data);

        if($cfg_member_grade_rule!=$data['cfg_member_grade_rule']){
            $grade_rules = $data['cfg_member_grade_rule']==3?2:1;
            DB::update('member_grade')->set(['grade_rules'=>$grade_rules])->execute();
            if($cfg_member_grade_rule==3 || $data['cfg_member_grade_rule']==3){
                $date = time()-86400;
                DB::update('member')->set(['grade_expire_time'=>$date])->where("grade_id!='' OR grade_id IS NOT NULL")->execute();
            }
        }

        echo json_encode([
            'status' => true
        ]);
    }
}